package com.veo.service;

import ch.qos.logback.core.util.TimeUtil;
import cn.hutool.core.util.IdUtil;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.aop.ThrowsAdvice;
import org.springframework.stereotype.Service;

import javax.print.attribute.standard.MediaSize;
import java.util.concurrent.TimeUnit;

@Service
public class PaymentService {

    public String paymentInfo_ok(Integer id){
        return "线程池id: "+Thread.currentThread().getName()+" , payment_ok , id: "+id+"\t"+"O(∩_∩)O哈哈~";
    }

    //服务降级
    @HystrixCommand(fallbackMethod = "paymentInfo_timeOutHandler",commandProperties = {
     @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "3000")
    })
    public String paymentInfo_timeOut(Integer id){
        //超时和方法异常，会调服务降级
//        int money =10 / 0;
        int timeout = 5;
        try {
            TimeUnit.SECONDS.sleep(timeout);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "线程池id: "+Thread.currentThread().getName()+" , payment_timeout , id: "+id+"\t"+"O(∩_∩)O哈哈~"+"耗时："+timeout;
    }

    //服务降级执行的方法
    public String paymentInfo_timeOutHandler(Integer id){
        return "线程池id: "+Thread.currentThread().getName()+" , paymentInfo_timeOutHandler,服务器繁忙，请稍后再试 , id: "+id+"\t"+"o(╥﹏╥)o";
    }

    //######服务熔断
    @HystrixCommand(fallbackMethod = "paymentCircuitBreak_fallBack",commandProperties = {
            @HystrixProperty(name = "circuitBreaker.enabled",value = "true"),//是否开启熔断器
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "10"),//请求次数
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "10000"),//时间窗口期
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "50"),//时间窗口期内的请求次数到达50%就开启熔断器
    })
    public String paymentCircuitBreak(Integer id){
        if(id < 0) {
            throw new RuntimeException("#########id,不可以为负数！");
        }
        String serialNumber = IdUtil.simpleUUID();
        return Thread.currentThread().getName()+"\t"+"调用成功，流水号："+serialNumber;
    }

    public String paymentCircuitBreak_fallBack(Integer id){
        return "id,不能为负，请稍后再试，(#^.^#)  id:"+id;
    }
}
